import { defineStore } from 'pinia'

export const usePiniaCounterStore = defineStore('piniaCounter', {
  state: () => ({
    count: 0,
    history: []
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
    lastChange: (state) => state.history[state.history.length - 1] ?? null
  },
  actions: {
    increment() {
      this.count++
      this.history.push({ type: 'inc', value: this.count, at: Date.now() })
    },
    decrement() {
      this.count--
      this.history.push({ type: 'dec', value: this.count, at: Date.now() })
    },
    setCount(val) {
      const n = Number(val) || 0
      this.count = n
      this.history.push({ type: 'set', value: n, at: Date.now() })
    },
    reset() {
      this.count = 0
      this.history.push({ type: 'reset', value: this.count, at: Date.now() })
    },
    undo() {
      if (this.history.length > 1) {
        this.history.pop()
        const last = this.history[this.history.length - 1]
        this.count = last.value
      }
    }
  }
})